﻿using System;
using System.Collections.Generic;
using System.Text;
using Gmmy.DomainExtension;
using Microsoft.EntityFrameworkCore;

namespace Gmmy.RepositoryExtension
{
   public static class DbContextExtensions
    {
        public static void AttachUpdated<T>(this DbContext obj, T objectDetached) where T : EntityBase
        {
            if (objectDetached == null) throw new ArgumentNullException();
            if (obj.Entry<T>(objectDetached).State == EntityState.Detached)
            {
                obj.Set<T>().Attach(objectDetached);
            }
        }
        public static IEnumerable<T> SqlQuery<T>(this DbContext db, string sql, params object[] parameters) where T : new()
        {
            //注意：不要对GetDbConnection获取到的conn进行using或者调用Dispose，否则DbContext后续不能再进行使用了，会抛异常 
            var conn = db.Database.GetDbConnection();
            try
            {
                conn.Open();
                using (var command = conn.CreateCommand())
                {
                    command.CommandText = sql;
                    if (parameters != null) { command.Parameters.AddRange(parameters); }
                    var propts = typeof(T).GetProperties();
                    var rtnList = new List<T>();
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var model = new T();
                            foreach (var l in propts)
                            {
                                var val = reader[l.Name];
                                l.SetValue(model, val == DBNull.Value ? null : val);
                            }
                            rtnList.Add(model);
                        }
                    }
                    return rtnList;
                }
            }
            finally
            {
                conn.Close();
            }
        }
    }
}
